package tree;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;

public class Tree2ListMain {

    public static void main(String[] args) {

        Tree t1 = new Tree(1, "A", null, new ArrayList<>());
        Tree t2 = new Tree(2, "A1", null, new ArrayList<>());
        Tree t3 = new Tree(3, "A11", null, new ArrayList<>());
        Tree t4 = new Tree(4, "A2", null, new ArrayList<>());
        Tree t5 = new Tree(5, "A21", null, new ArrayList<>());
        Tree t6 = new Tree(6, "A22", null, new ArrayList<>());

        t1.getChildren().add(t2);
        t1.getChildren().add(t4);

        t2.getChildren().add(t3);
        t4.getChildren().add(t5);
        t4.getChildren().add(t6);
        List<Tree> arrayList = new ArrayList<>();
        arrayList.add(t1);

        System.out.println("------以上是初始化数据------");

        // 树转集合
        List<Tree> tree2line = tree2list(arrayList);

        System.out.println("------转换完毕------");
        tree2line.forEach(System.out::println);
    }

    public static List<Tree> tree2list(List<Tree> tree) {
        List<Tree> treeNode = new ArrayList<>();
        List<Tree> lineNode = new ArrayList<>();
        for (int i = 0; i < tree.size(); ) {
            Tree t = new Tree();
            BeanUtils.copyProperties(tree.get(i), t, "children");
            lineNode.add(t);
            if (tree.get(i).getChildren().size() > 0) {
                treeNode.addAll(tree.get(i).getChildren());
            }
            if (tree.size() == (i + 1)) {
                tree = treeNode;
                treeNode = new ArrayList<>();
                i = 0;
            } else {
                i++;
            }
        }
        return lineNode;
    }
}
